<?php
/**
 * 公共的工具类
 */

namespace common\utils;


use common\component\CacheHelper;
use common\component\Constant;
use common\models\info\Article;
use common\models\info\Category;
use common\models\info\Tags;
use common\models\messager\Notify;
use yii\helpers\Url;
use yii\web\HttpException;

class CommonUtil
{
    /**
     * 获取缓存
     * @param $clazz 用到缓存的类
     * @param $key 配置文件中对应的KEY
     * @return mixed
     */
    public static function getCache($clazz,$key) {
        return CacheHelper::getInstance($clazz,$key)->getCache();
    }

    /**
     * 设置缓存
     * @param object $clazz 用到缓存的类
     * @param string $key 配置文件中对应的KEY
     * @param mixed $data 存入的值
     * @param int $expire 过期时间
     * @return mixed
     */
    public static function setCache($clazz,$key,$data,$expire = 0) {
        return CacheHelper::getInstance($clazz,$key,$expire)->setCache($data);
    }
    /**
     * 过滤字符
     * @param $data array
     * @param bool $ucfirst
     */
    public static function enSlashesData(&$data,$ucfirst = false) {
        if (!count($data)) return;
        foreach ( $data as $key => $value ) {
            if (is_array ( $value )) {
                foreach ( $value as $kkk => $vvv ) {
                    if (is_array ( $vvv )) {
                        foreach ( $vvv as $kk => $vv ) {
                            if (is_array ( $vv )) {
                                foreach ( $vv as $k => $v ) {
                                    if (is_array ( $v )) {
                                        throw new HttpException(403,"错误的请求参数");
                                    } else {
                                        $data [$key] [$kkk] [$kk] [$k] = self::enSlashes ( trim($v), $ucfirst );
                                    }
                                }
                            } else {
                                $data [$key] [$kkk] [$kk] = self::enSlashes ( trim($vv), $ucfirst );
                            }
                        }
                    } else {
                        $data [$key] [$kkk] = self::enSlashes ( trim($vvv), $ucfirst );
                    }
                }
            } else {
                $data [$key] = self::enSlashes ( trim($value), $ucfirst );
            }
        }
        return $data;
    }

    /**
     * 数据转换成有[&#]
     */
    public static function enSlashes($value, $ucfirst = false) {
        if (empty ( $value )) {
            return $value;
        }
        //过滤不完整的utf8字符
        if(mb_check_encoding($value,'GBK') !== true){
            $value=self::filterPartialUTF8Char($value);
        }
        if(mb_check_encoding($value,'GBK') == false && mb_check_encoding($value,'UTF-8') == false){
            return '';
        }
        if (mb_check_encoding($value,'GBK') == true && mb_check_encoding($value,'UTF-8')!==true){
            $value = mb_convert_encoding($value, 'UTF-8', 'GBK');
        }
        if(strpos($value,'&')!==false){
            $value =htmlspecialchars_decode($value, ENT_QUOTES|ENT_NOQUOTES);
        }
        $filters = array ('&' => '&#' . ord ( '&' ) . ';', '#' => '&#' . ord ( '#' ) . ';', ' ' => '&#' . ord ( ' ' ) . ';', '\'' => '&#' . ord ( '\'' ) . ';', '>' => '&#' . ord ( '>' ) . ';',
            '<' => '&#' . ord ( '<' ) . ';', '=' => '&#' . ord ( '=' ) . ';', '!' => '&#' . ord ( '!' ) . ';', '^' => '&#' . ord ( '^' ) . ';', '+' => '&#' . ord ( '+' ) . ';',
            '-' => '&#' . ord ( '-' ) . ';', '*' => '&#' . ord ( '*' ) . ';', '/' => '&#' . ord ( '/' ) . ';', '%' => '&#' . ord ( '%' ) . ';', '|' => '&#' . ord ( '|' ) . ';',
            '~' => '&#' . ord ( '~' ) . ';', '@' => '&#' . ord ( '@' ) . ';','"' => '&#' . ord ( '"' ) . ';',';' => '&#' . ord ( ';' ) . ';' );
        $value = strtr ( $value, $filters );
        if(strpos($value,'&#38;&#35;')!==false){//如果本身就含转义字符
            $value=str_replace('&#38;&#35;','&#',$value);
        }
        if ($ucfirst === true) {
            $value = strtolower ( $value );
        }
        return $value;

    }

    /**
     * 过滤不完整的utf8编码字符
     * @param string $str
     * @return string
     */
    public static function filterPartialUTF8Char($str){
        $str = preg_replace("/[\\xC0-\\xDF](?=[\\x00-\\x7F\\xC0-\\xDF\\xE0-\\xEF\\xF0-\\xF7]|$)/", "", $str);
        $str = preg_replace("/[\\xE0-\\xEF][\\x80-\\xBF]{0,1}(?=[\\x00-\\x7F\\xC0-\\xDF\\xE0-\\xEF\\xF0-\\xF7]|$)/", "", $str);
        $str = preg_replace("/[\\xF0-\\xF7][\\x80-\\xBF]{0,2}(?=[\\x00-\\x7F\\xC0-\\xDF\\xE0-\\xEF\\xF0-\\xF7]|$)/", "", $str);
        return $str;
    }

    /**
     * 有[&#]的数据转换成正常数据
     */
    public static function deSlashes($value, $ucfirst = false) {
        if (empty ( $value )) {
            return $value;
        }
        if(mb_check_encoding($value,'GBK') !== true){
            $value=self::filterPartialUTF8Char($value);
        }
        if(mb_check_encoding($value,'GBK') == false && mb_check_encoding($value,'UTF-8') == false){
            return '';
        }
        if (mb_check_encoding($value,'GBK') == true && mb_check_encoding($value,'UTF-8')!==true){
            $value = mb_convert_encoding($value, 'UTF-8', 'GBK');
        }
        if(strpos($value,'&')!==false){
            $value =htmlspecialchars_decode($value, ENT_QUOTES|ENT_NOQUOTES);
        }
        if(strpos($value,'&#')===false){
            return $value;
        }

        $filters = array ('&' => '&#' . ord ( '&' ) . ';', '#' => '&#' . ord ( '#' ) . ';', ' ' => '&#' . ord ( ' ' ) . ';', '\'' => '&#' . ord ( '\'' ) . ';', '>' => '&#' . ord ( '>' ) . ';',
            '<' => '&#' . ord ( '<' ) . ';', '=' => '&#' . ord ( '=' ) . ';', '!' => '&#' . ord ( '!' ) . ';', '^' => '&#' . ord ( '^' ) . ';', '+' => '&#' . ord ( '+' ) . ';',
            '-' => '&#' . ord ( '-' ) . ';', '*' => '&#' . ord ( '*' ) . ';', '/' => '&#' . ord ( '/' ) . ';', '%' => '&#' . ord ( '%' ) . ';', '|' => '&#' . ord ( '|' ) . ';',
            '~' => '&#' . ord ( '~' ) . ';', '@' => '&#' . ord ( '@' ) . ';','"' => '&#' . ord ( '"' ) . ';',';' => '&#' . ord ( ';' ) . ';' );
        $value = strtr ( $value, array_flip ( $filters ) );
        if ($ucfirst === true) {
            $value = strtolower ( $value );
        }
        return $value;

    }

    public static function buildRandomNumber($length = 6) {
        // 密码字符集，可任意添加你需要的字符
        $chars = array( '1', '2', '3', '4', '5', '6', '7', '8', '9','0');
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = "";
        for ($i=0; $i<$length; $i++)
        {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }

    public static function formatTime($timer) {
        $str = '';
        $timer = $timer?:0;
        $diff = $_SERVER['REQUEST_TIME'] - $timer;
        $year = floor($diff / 31536000);
        $day = floor($diff / 86400);
        $free = $diff % 86400;
        if ($year > 0) {
            return $year."年前";
        }elseif ($day > 0) {
            if ($day < 30) {
                return $day."天前";
            } else {
                return floor($day / 30) . "个月前";
            }
        }else{
            if($free>0){
                $hour = floor($free / 3600);
                $free = $free % 3600;
                if($hour>0){
                    return $hour."小时前";
                }else{
                    if($free>0){
                        $min = floor($free / 60);
                        $free = $free % 60;
                        if($min>0){
                            return $min."分钟前";
                        }else{
                            if($free>0){
                                return $free."秒前";
                            }else{
                                return '刚刚';
                            }
                        }
                    }else{
                        return '刚刚';
                    }
                }
            }else{
                return '刚刚';
            }
        }
    }


    /**
     * 中文字符串截取
     * @param string    $string  需要截取的字符串
     * @param int       $length  截取的长度
     * @param string    $etc     被截取的部分替换的字符串
     * @param bool    $encry     是否需要返回转义后的字符串
     * @return string
     */
    public static function cutString($string, $length, $etc = '...', $charset = 'UTF-8' ,$encry = true) {
        $string=  self::deSlashes($string);
        $trans=array('&#38;nbsp&#59;'=>' ', '&nbsp;'=>' ');
        $string=strtr($string, $trans);
        $string = trim(strip_tags($string));
        $string=mb_strimwidth($string, 0, $length*2, $etc, $charset);
        strpos($string,' ')!==false && $string = str_replace(' ','&nbsp;',$string);
        if($encry){
            $string = self::enSlashes($string);
        }
        strpos($string,'&#38;nbsp&#59;')!==false && $string = str_replace('&#38;nbsp&#59;','&nbsp;',$string);
        return $string;
    }
    /**
     * RGB转 十六进制
     * @param $rgb RGB颜色的字符串 如：rgb(255,255,255);
     * @return string 十六进制颜色值 如：#FFFFFF
     */
    public static function captchaColor($type = 1) {
        if(!in_array($type, array(1,2))) $type=1;
        if($type==1) {
            $bg_color_arr=array('15595519','16316664','15792383','16444375','15794175','16119260','16770244','14596231','16775388','16775920','15794160','15132410','14745599');
            $bg=$bg_color_arr[array_rand($bg_color_arr)];
            return (int) '0x'.$bg;
        } else {
            $text_color_arr=array('12326852','2185586','10506797','9055202','10824234','6591981','5597999','9109504','4734347','4915330','1644912');
            $tc=$text_color_arr[array_rand($text_color_arr)];
            return (int) '0x'.$tc;
        }
    }

    public static function generateUrl($id,$route_type="",$default="",$page=1,$appEnd='') {
        $url = '{link}';
        switch ($route_type) {
            case Constant::ROUTE_USER:
                $url = preg_replace("/{link}/",Url::to(["/home/$id"]),$url);
                break;
            case Constant::ROUTE_ARTICLE:
                $url = preg_replace("/{link}/",Url::to(["/article/$id.html"]),$url);
                break;
            case Constant::ROUTE_PHOTO:
                $url = preg_replace("/{link}/",Url::to(["/album/$id.html"]),$url);
                break;
            case Constant::ROUTE_TAG:
                $url = preg_replace("/{link}/",Url::to(["/tag/$id.html"]),$url);
                break;
            case Constant::ROUTE_CATEGORY:
                $url = preg_replace("/{link}/",Url::to(["/category/$id.html"]),$url);
                break;
            default:
                $url = $default;
        }
        return $url;
    }

    public static function buildUrl($id,$target_type="",$value="") {
        $url = '{link}';
        switch ($target_type) {
            case Notify::TARGET_USER:
                $url = preg_replace("/{link}/",Url::to(["/home-$id"]),$url);
                break;
            case Notify::TARGET_ARTICLE:
                $url = preg_replace("/{link}/",Url::to(["/article-$id"]),$url);
                break;
            case Notify::TARGET_TAG:
                $url = preg_replace("/{link}/",Url::to(["/tag-$id"]),$url);
                break;
            default:
                $url = $value;
        }
        return $url;
    }
    public static function currentDomain()
    {
        $domain = ($pos = strpos($_SERVER['HTTP_HOST'],":"))?substr($_SERVER['HTTP_HOST'],0,$pos):$_SERVER['HTTP_HOST'];
        return $domain;
    }
    /*
     * 从开始年到当前年列表
     */
    public static function distanceYear($startYear) {
        $currentYear = (int)date('Y');
        $yearArr = [];
        do {
            $yearArr[] = $startYear++;
        }while($startYear <= $currentYear);
        arsort($yearArr);
        return $yearArr;
    }

}
